<template>
  <el-dialog
    v-model="createOrEditVisible"
    :title="props.isEdit ? '编辑' : '创建'"
    destroy-on-close
    width="480"
    custom-class="no-header-dialog"
  >
    <div class="modal-create-or-edit">
      <el-form ref="createOrEditForm" :model="modalForm" :rules="modalFormRule" label-width="auto">
        <el-form-item label="接入系统类型：" prop="type">
          <el-select ref="role" v-model="modalForm.type" :disabled="props.isEdit" placeholder="请选择">
            <el-option value="" key="" title="请选择">请选择</el-option>
            <el-option v-for="item of sysTypeList" :value="item.key" :key="item.key" :title="item.value" :label="item.value">{{
              item.value
            }}</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="对接系统名称：" prop="name">
          <el-input v-model="modalForm.name" placeholder="请输入对接系统中所显示的名称（不超过64个字符）" />
        </el-form-item>
        <el-form-item label="主机地址：" prop="host">
          <el-input v-model="modalForm.host" placeholder="请输入（不超过255个字符）" />
        </el-form-item>
        <el-form-item label="协议：" prop="protocol">
          <el-radio-group v-model="modalForm.protocol">
            <el-radio value="http"> http </el-radio>
            <el-radio value="https"> https </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="端口号：" prop="port">
          <el-input-number v-model="modalForm.port" :min="0" :max="65535" placeholder="请输入端口号（不超过65535）" />
          <!-- <el-input v-model="modalForm.port" placeholder="请输入端口号（不超过65535）" /> -->
        </el-form-item>
        <el-form-item label="license到期日" prop="lisense_end_time" placeholder="请选择license到期日">
          <el-date-picker v-model="modalForm.lisense_end_time" />
        </el-form-item>
        <el-form-item label="用户名：" prop="username">
          <el-input v-model="modalForm.username" placeholder="请输入（不超过255个字符）" />
        </el-form-item>
        <el-form-item label="密码：" prop="password">
          <el-input v-model="modalForm.password" placeholder="请输入（不超过255个字符）" />
        </el-form-item>
        <el-form-item label="所属线路：">
          <el-select v-model="modalForm.route_id" show-search allow-clear placeholder="请选择" show-arrow>
            <el-option v-for="item of routeList" :value="item.id" :key="item.id" :title="item.name" :label="item.name">{{
              item.name
            }}</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="ar地址：" prop="ar_sso_path" v-if="modalForm.type === 'cloudBackup'">
          <el-input v-model="modalForm.ar_sso_path" placeholder="请输入（不超过255个字符）" />
        </el-form-item>
        <el-form-item label="代理：" prop="proxy_info">
          <el-select ref="role" v-model="modalForm.proxy_info" show-search allow-clear placeholder="请选择" show-arrow multiple>
            <el-option v-for="item of proxyList" :value="item" :key="item" :title="item" :label="item">{{ item }}</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="对接平台名称：" prop="sxf_platform_name" v-if="modalForm.type === 'cloudSecurity'">
          <el-input v-model="modalForm.sxf_platform_name" placeholder="请输入对接平台名称" />
        </el-form-item>
        <el-form-item label="API键值：" prop="apikey" v-if="modalForm.type === 'BastionHostSangfor'">
          <el-input v-model="modalForm.apikey" placeholder="请输入API键值" />
        </el-form-item>
        <el-form-item label="登录页地址：" prop="login_address" v-if="modalForm.type === 'cloudOM'">
          <el-input v-model="modalForm.login_address" placeholder="请输入登录页地址" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="modal-create-or-edit-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" :loading="loadingSubmit" @click="submit(createOrEditForm)">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="createOrEdit">
import { reactive, ref, nextTick } from "vue";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { validate } from "@/utils/validate";
import { modifyThirdSystem, addThirdSystem, getEnums } from "@/api/modules/businessManagement/thirdPartyManagement";
import { getRouterListApi } from "@/api/modules/sysManagement/routeManage";
const createOrEditVisible = ref<boolean>(false);
const openDialog = () => {
  modalForm.value = {};
  nextTick(() => {
    if (props.isEdit) {
      initialEditForm();
    }
  });
  getType();
  getRouterList();
  createOrEditVisible.value = true;
};
const closeDialog = () => {
  createOrEditVisible.value = false;
};
const createOrEditForm = ref<FormInstance>();
const modalForm = ref<any>({
  type: "",
  name: "",
  route_id: null,
  username: "",
  password: "",
  protocol: "",
  host: "",
  ar_sso_path: "",
  port: "",
  proxy_info: [],
  sxf_platform_name: "",
  lisense_end_time: null,
  apikey: "",
  login_address: ""
});
const modalFormRule = reactive<FormRules>({
  type: [{ required: true, message: "内容不能为空", trigger: ["blur", "change"] }],
  name: [
    { required: true, message: "内容不能为空", trigger: ["blur", "change"] },
    { min: 0, max: 64, message: "不超过64个字符", trigger: ["blur", "change"] }
  ],
  username: [
    // { required: true, message: '内容不能为空', trigger: ['blur', 'change'] },
    { min: 0, max: 255, message: "不超过255个字符", trigger: ["blur", "change"] }
  ],
  password: [
    // { required: true, message: '内容不能为空', trigger: ['blur', 'change'] },
    { min: 0, max: 255, message: "不超过255个字符", trigger: ["blur", "change"] }
  ],
  protocol: [{ required: true, message: "内容不能为空", trigger: ["blur", "change"] }],
  host: [
    { required: true, message: "内容不能为空", trigger: ["blur", "change"] }
    // { required: false, pattern: validate.filterIPAddress, message: '请输入正确的ip地址, 例如: 192.168.1.0', trigger: ['blur', 'change'] }
  ],
  ar_sso_path: [
    { required: true, message: "内容不能为空", trigger: ["blur", "change"] },
    {
      required: false,
      pattern: validate.filterIPAddress,
      message: "请输入正确的ar地址, 例如: 192.168.1.0",
      trigger: "blur"
    },
    {
      required: false,
      pattern: validate.filterIPAddress,
      message: "请输入正确的ar地址, 例如: 192.168.1.0",
      trigger: "change"
    }
  ],
  port: [
    { required: true, message: "内容不能为空", trigger: "blur", type: "number" },
    { message: "请输入0-65535的整数", trigger: "blur", pattern: validate.filterPort }
  ],
  sxf_platform_name: [{ required: true, message: "内容不能为空", trigger: ["blur", "change"] }],
  apikey: [
    { required: true, message: "内容不能为空", trigger: ["blur", "change"] },
    { min: 0, max: 255, message: "不超过255个字符", trigger: ["blur", "change"] }
  ]
});
const props = defineProps({
  isEdit: {
    type: Boolean,
    default: () => false
  },
  editItem: {
    type: Object,
    default: () => ({})
  }
});
// const props = {
//   isEdit: {
//     type: Boolean,
//     default: () => false
//   },
//   editItem: {
//     type: Object,
//     default: () => ({})
//   }
// };
const emit = defineEmits<{
  submit: [];
}>();
const sysTypeList = ref<any>([]);
const routeList = ref<any>([]);
const proxyList = ref<any>(["http://10.167.48.58:1080", "https://10.167.48.58:1080"]);
const loadingSubmit = ref<boolean>(false);
const submit = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (valid) {
      loadingSubmit.value = true;
      const eles = JSON.parse(JSON.stringify(modalForm.value));
      switch (eles.type) {
        case "cloudOM":
        case "netHuawei":
          delete eles.sxf_platform_name;
          break;
        default:
          const proxyInfo = {};
          modalForm.value["proxy_info"].forEach(item => {
            const ele = item.split("://");
            proxyInfo[ele[0]] = "socks5://" + ele[1];
          });
          eles["proxy_info"] = proxyInfo;
      }
      eles["route_id"] = parseInt(eles.route_id);
      modalForm.value.type === "cloudOM" ? null : delete eles.login_address;
      if (props.isEdit) {
        try {
          const res = await modifyThirdSystem(eles, props.editItem.id);
          if (res) {
            ElMessage.success("编辑成功");
            loadingSubmit.value = false;
            emit("submit");
            closeDialog();
          }
        } catch (error: any) {
          let str = "";
          if (error.response && error.response.data && error.response.data.message) {
            str = error.response.data.message;
          }
          ElMessage.error("编辑失败" + (str.length > 0 ? ": " + str : ""));
          loadingSubmit.value = false;
        }
      } else {
        try {
          const res = await addThirdSystem(eles);
          if (res) {
            ElMessage.success("接入成功");
            loadingSubmit.value = false;
            emit("submit");
            closeDialog();
          }
        } catch (error: any) {
          loadingSubmit.value = false;
        }
      }
    }
  });
};
const initialEditForm = () => {
  const hwProxyInfo: any = [];
  if (props.editItem["proxy_info"]) {
    Object.keys(props.editItem["proxy_info"]).forEach(key => {
      hwProxyInfo.push(key + "://" + props.editItem["proxy_info"][key].split("://")[1]);
    });
  }
  modalForm.value = {
    type: props.editItem.type.key,
    name: props.editItem.name,
    username: props.editItem.username,
    password: props.editItem.password,
    protocol: props.editItem.protocol,
    host: props.editItem.host,
    ar_sso_path: props.editItem.ar_sso_path,
    port: parseInt(props.editItem.port),
    sxf_platform_name: props.editItem["sxf_platform_name"],
    proxy_info: hwProxyInfo.length > 0 ? hwProxyInfo : [],
    route_id: props.editItem.route ? props.editItem.route.id : null,
    lisense_end_time: props.editItem.lisense_end_time ? props.editItem.lisense_end_time : null,
    apikey: props.editItem.apikey,
    login_address: props.editItem["sso_path"] ? props.editItem["sso_path"] : ""
  };
};
const getType = async () => {
  try {
    const { data } = await getEnums();
    sysTypeList.value = data.third_system_type;
  } catch (error: any) {
    let str = "";
    if (error.response && error.response.data && error.response.data.message) {
      str = error.response.data.message;
    }
    ElMessage.error("对接系统类型查询失败" + (str.length > 0 ? ": " + str : ""));
  }
};
// 查询线路
const getRouterList = async () => {
  routeList.value = [];
  try {
    const { data } = await getRouterListApi();
    if (data) routeList.value = data["results"];
  } catch (error: any) {
    let str = "";
    if (error.response && error.response.data && error.response.data.message) {
      str = error.response.data.message;
    }
    ElMessage.error("查询失败" + (str.length > 0 ? ": " + str : ""));
  }
};
defineExpose({
  openDialog,
  closeDialog
});
</script>

<style lang="scss" scoped>
.modal-create-or-edit {
  :deep(.ant-form-item-label) {
    width: 110px !important;
  }
}
.modal-create-or-edit-footer {
  text-align: right;
}
:deep(.ant-transfer-list-body-not-found) {
  img {
    display: none;
  }
}
:deep(.ant-transfer) {
  .ant-btn {
    width: 24px;
    min-width: 24px;
    max-width: 24px;
    margin-right: 0;
    margin-left: 0;
  }
}
</style>
